from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from .models import OpticalDistributionFrame, Board, Interface
from .serializers import OpticalDistributionFrameSerializer, BoardSerializer, InterfaceSerializer

# 光交箱视图集
class OpticalDistributionFrameViewSet(viewsets.ModelViewSet):
    """
    光交箱视图集，提供获取、创建、更新和删除光交箱的接口。
    """
    queryset = OpticalDistributionFrame.objects.all()
    serializer_class = OpticalDistributionFrameSerializer

# 光路板视图集
class BoardViewSet(viewsets.ModelViewSet):
    """
    光路板视图集，提供获取、创建、更新和删除光路板的接口。
    """
    queryset = Board.objects.all()
    serializer_class = BoardSerializer

# 光口视图集
class InterfaceViewSet(viewsets.ModelViewSet):
    """
    光口视图集，提供获取、创建、更新和删除光口的接口。
    """
    queryset = Interface.objects.all()
    serializer_class = InterfaceSerializer

# 连接光口的 API
@api_view(['POST'])
def connect_interfaces(request):
    """
    连接两个光口的 API。
    """
    interface1_id = request.data.get('interface1_id')
    interface2_id = request.data.get('interface2_id')

    try:
        interface1 = Interface.objects.get(id=interface1_id)
        interface2 = Interface.objects.get(id=interface2_id)

        # 检查接口是否已经连接
        if interface1.connected_interface or interface2.connected_interface:
            return Response({'error': 'One or both interfaces are already connected.'}, status=status.HTTP_400_BAD_REQUEST)

        # 更新接口连接状态
        interface1.connected_interface = interface2
        interface1.status = 'in_use'
        interface2.status = 'in_use'
        interface1.save()
        interface2.save()

        return Response({'message': 'Interfaces connected successfully'}, status=status.HTTP_201_CREATED)

    except Interface.DoesNotExist:
        return Response({'error': 'Interface not found'}, status=status.HTTP_404_NOT_FOUND)

# 断开光口的 API
@api_view(['POST'])
def disconnect_interfaces(request):
    """
    断开光口的 API。
    """
    interface_id = request.data.get('interface_id')

    try:
        interface = Interface.objects.get(id=interface_id)

        # 检查接口是否已经连接
        if not interface.connected_interface:
            return Response({'error': 'Interface is not connected.'}, status=status.HTTP_400_BAD_REQUEST)

        # 更新接口连接状态
        interface.connected_interface = None
        interface.status = 'available'
        interface.save()

        return Response({'message': 'Interface disconnected successfully'}, status=status.HTTP_200_OK)

    except Interface.DoesNotExist:
        return Response({'error': 'Interface not found'}, status=status.HTTP_404_NOT_FOUND)
